package org.ysling.litemall.admin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.ysling.litemall.admin.util.Permission;
import org.ysling.litemall.admin.util.PermissionUtil;
import org.ysling.litemall.db.vomain.PermVo;

import java.util.*;

@Service
public class SystemPermissionsService {

    @Autowired
    private ApplicationContext context;

    private Set<String> systemPermissionsSet = null;
    private List<PermVo> systemPermissionList = null;
    private HashMap<String, String> systemPermissionsMap = null;

    public Set<String> getSystemPermissionsSet() {
        return systemPermissionsSet;
    }

    public Collection<String> toApi(Set<String> permissions) {
        if (systemPermissionsMap == null) {
            systemPermissionsMap = new HashMap<>();
            final String basicPackage = "org.ysling.litemall.admin";
            List<Permission> systemPermissions = PermissionUtil.listPermission(context, basicPackage);
            for (Permission permission : systemPermissions) {
                String perm = permission.getRequiresPermissions().value()[0];
                String api = permission.getApi();
                systemPermissionsMap.put(perm, api);
            }
        }

        Collection<String> apis = new HashSet<>();
        for (String perm : permissions) {
            String api = systemPermissionsMap.get(perm);
            apis.add(api);

            if (perm.equals("*")) {
                apis.clear();
                apis.add("*");
                return apis;
            }
        }
        return apis;
    }

    public List<PermVo> getSystemPermissions() {
        final String basicPackage = "org.ysling.litemall.admin";
        if (systemPermissionList == null) {
            List<Permission> permissions = PermissionUtil.listPermission(context, basicPackage);
            systemPermissionList = PermissionUtil.listPermVo(permissions);
            systemPermissionsSet = PermissionUtil.listPermissionString(permissions);
        }
        return systemPermissionList;
    }

}
